package repo

import (
	log "github.com/sirupsen/logrus"
	model "micro-oauth/datamodels"
	"micro-oauth/datamodels/params"
)

func (s *ServiceImpl) GetDeviceByUUID(uuid string) *model.Device {
	var device = new(model.Device)

	db := s.db.Where("uuid = ?", uuid).First(device)
	if db.RecordNotFound() {
		return nil
	}
	if db.Error != nil {
		log.Error("get device from db error : ", db.Error)
		return nil
	}
	return device
}
func (s *ServiceImpl) GetDeviceById(id uint64) *model.Device {
	var device = new(model.Device)

	db := s.db.Where("id = ?", id).First(device)
	if db.RecordNotFound() {
		return nil
	}
	if db.Error != nil {
		log.Error("get device from db error : ", db.Error)
		return nil
	}
	return device
}

func (s *ServiceImpl) AddDevice(device *model.Device) error {
	return s.db.Create(device).Error
}

func (s *ServiceImpl) UpdateDevice(device *model.Device) error {
	return s.db.Save(device).Error
}

func (s *ServiceImpl) DeleteDevice(deviceId uint64) error {
	return s.db.Where("id = ?", deviceId).Delete(model.Device{}).Error
}

func (s *ServiceImpl) ListDevice(partnerId, scopeId uint64, req *params.DeviceListRequest) (devices []*model.Device, total uint64, err error) {
	db := DefaultListDB(s.db, &req.ListRequest)
	if req.Status != "" {
		db = db.Where("status = ?", req.Status)
	}
	db = db.Where("scope_id = ?", scopeId)
	if req.Remark != "" {
		db = db.Where("remark ilike ?", "%"+req.Remark+"%")
	}
	if req.UUID != "" {
		db = db.Where("uuid ilike ?", "%"+req.UUID+"%")
	}
	db.Model(&model.Device{}).Count(&total)
	if req.Limit != 0 {
		db = db.Limit(req.Limit)
	}
	if req.Offset != 0 {
		db = db.Offset(req.Offset)
	}
	err = db.Find(&devices).Error
	if err != nil {
		return nil, 0, err
	}
	return devices, total, nil
}
